/*
 * FileGridAdapter.java
 * classes : com.ruint.lib.mediachooser.adapter.FileGridAdapter
 * @author ruint
 * V 1.0.0
 * Create at 2014-12-4 下午3:27:02
 */
package com.ruint.lib.mediachooser.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;

import com.ruint.core.adapter.BaseListAdapter;
import com.ruint.core.utils.ViewHolder;
import com.ruint.core.utils.bitmap.ImageLoaderUtils;
import com.ruint.core.utils.bitmap.ImageLoaderUtils.ImageLoaderCompleteListener;
import com.ruint.corelib.R;
import com.ruint.lib.mediachooser.bean.MediaModel;

/**
 * com.ruint.lib.mediachooser.adapter.FileGridAdapter
 * 
 * @author ruint <br/>
 *         create at 2014-12-4 下午3:27:02
 */
public class FileGridAdapter extends BaseListAdapter<MediaModel> {

  private int mWidth;

  /**
   * @param context
   */
  public FileGridAdapter(Context context) {
    super(context);
    mWidth = context.getResources().getDisplayMetrics().widthPixels;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
      convertView = LayoutInflater.from(context).inflate(R.layout.view_grid_file_item, parent, false);
    }
    final ImageView image = ViewHolder.get(convertView, R.id.file_image_item);
    LayoutParams imageParams = (LayoutParams) image.getLayoutParams();
    imageParams.width = mWidth / 2;
    imageParams.height = mWidth / 2;
    image.setLayoutParams(imageParams);
    if (mList != null && mList.size() > 0) {
      final MediaModel media = mList.get(position);
      ImageLoaderUtils.getInstance().loadImage(media.getUrl(), new ImageLoaderCompleteListener() {

        @SuppressLint("NewApi")
        @SuppressWarnings("deprecation")
        @Override
        public void onCompleteImageLoader(Bitmap bitmap) {
          if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            image.setBackgroundDrawable(new BitmapDrawable(context.getResources(), bitmap));
          } else {
            image.setBackground(new BitmapDrawable(context.getResources(), bitmap));
          }
          if (media.isSelected()) {
            image.setImageResource(R.drawable.bg_img_selected);
          } else {
            image.setImageResource(R.drawable.bg_img_unselected);
          }
        }
      });

    }
    return convertView;
  }
}
